﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using PLCSimulator.Views;
namespace PLCSimulator.Editor
{
    public class Editor : ObservableObject
    {
        public Editor(EditorDiagramView canvas)
        {
            this.Diagram = canvas;
        }
        private ObservableCollection<IDescriptor> _descriptors = new ObservableCollection<IDescriptor> {
            new ButtonDescriptor(),
            new ButtonDescriptor()
        };
        public EditorDiagramView Diagram { get; set; }
        public ObservableCollection<IDescriptor> Descriptors
        {
            get { return _descriptors; }
            set { _descriptors = value; OnPropertyChanged(); }
        }

        FrameworkElement? _dragSource;
        protected static readonly string CircuitDescriptorDataFormat = "PLCSimulator.Descriptor." + Environment.ProcessId;
        public void DescriptorMouseDown(FrameworkElement sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                if (sender.DataContext is IDescriptor)
                {
                    this._dragSource = sender;
                    DragDrop.DoDragDrop(sender,
                        new DataObject(CircuitDescriptorDataFormat, sender.DataContext),
                        DragDropEffects.Copy | DragDropEffects.Scroll
                    );
                }
            }
        }

        public void DescriptorMouseUp()
        {
            this._dragSource = null;
        }

        public void DescriptorMouseMove(object sender, MouseEventArgs e)
        {

        }

        public void DiagramDrop(DragEventArgs e)
        {
            if (e.Data.GetData(CircuitDescriptorDataFormat, false) is IDescriptor descriptor)
            {
                descriptor.CreateSymbol(this, Diagram, e.GetPosition(this.Diagram));
            }
        }
    }
}
